import { http } from '@/server'
import { useEffect, useRef, useState } from 'react'

/** 场景ID */
const CaptchaSceneID = '9pldoyg7'
/** 身份标 */
const CaptchaPrefix = '1d012i'

export interface VerifyResult {
    RequestId: string
    Result: {
        VerifyCode: string
        VerifyResult: boolean
    }
}

export const useAliyunCaptcha = ({
    onBizResultCallback,
    options,
}: {
    onBizResultCallback: (result: boolean) => void
    options?: Partial<InitAliyunCaptchaOptions>
}) => {
    const captchaInstance = useRef<CaptchaInstance>()
    const [verifyResult, setVerifyResult] = useState<VerifyResult>()

    const captchaVerifyCallback = async (captchaVerifyParam: string) => {
        const { data } = await http.post<VerifyResult>('/resource/verify-captcha', {
            verify_params: captchaVerifyParam,
        })
        setVerifyResult(data)
        return {
            captchaResult: data.Result.VerifyResult,
            bizResult: data.Result.VerifyResult,
        }
    }

    useEffect(() => {
        // 只用初始化一次验证码即可
        window.initAliyunCaptcha({
            SceneId: CaptchaSceneID,
            prefix: CaptchaPrefix,
            mode: 'popup',
            element: '#captcha-element',
            button: '#captcha-button',
            captchaVerifyCallback: captchaVerifyCallback,
            onBizResultCallback: onBizResultCallback,
            getInstance: (instance: CaptchaInstance) => {
                captchaInstance.current = instance
            },
            slideStyle: {
                width: 320,
                height: 32,
            },
            immediate: true,
            ...options,
        })

        return () => {
            // 必须删除相关元素，否则再次mount多次调用 initAliyunCaptcha 会导致多次回调 captchaVerifyCallback
            document.getElementById('aliyunCaptcha-mask')?.remove()
            document.getElementById('aliyunCaptcha-window-popup')?.remove()
        }
    }, [options, onBizResultCallback])

    return {
        captchaInstance,
        verifyResult,
    }
}
